const MongoClient = require("mongodb").MongoClient;

//连接URL
const URL = "mongodb://localhost:27017";
//数据库名称
const dbName = "SuperMall";
//创建MongoClient客户端连接
client = new MongoClient(URL, {
  useNewUrlParser: true,
  useUnifiedTopology: true,
});
client.connect((err) => {
  if (err) {
    console.log("error Messages is" + err.stack);
    return;
  }
  console.log("连接MongoDB数据库成功");

  db = client.db(dbName);
});

//查找全部文档
const findDocuments = (docmentName, callback) => {
  //数据库实例，文档名称,回调函数
  //获取集合
  const documents = db.collection(docmentName);
  documents.find({}).toArray((err, result) => {
    //console.log(result);
    callback(result);
  });
};

//分片查询
const findDocumentsLimit = (docmentName, limit, callback) => {
  const documents = db.collection(docmentName);
  documents
    .find({})
    .limit(limit)
    .toArray((err, result) => {
      callback(result);
    });
};

//插入文档
const insertDocuments = (documentName, data, callback) => {
  const doc = db.collection(documentName);
  doc.insert(data, (err, result) => {
    console.log("已经插入文档，响应结果是：");
    console.log("影响条数:", result.result.n);
    callback();
  });
};
//根据id查找文档
const findDocumentsById = function (documentName, id, callback) {
  const doc = db.collection(documentName);
  doc.find({ _id: require("mongodb").ObjectID(id) }).toArray((err, result) => {
    callback(result);
  });
};
//根据用户名查找文档
const findDocumentByName = function (name, callback) {
  const doc = db.collection("users");
  doc.find({ name: name }).toArray((err, result) => {
    if (err) console.log(err);
    callback(result);
  });
};
//对比用户名和密码 登录
const findDocmentByInfo = function(name,password,callback){
  const doc = db.collection("users");

  doc.find({name:name,password:password}).toArray((err,result)=>{
    if (err) console.log("findDocmentByInfo 方法",err);
    callback(result);
  })
}


//关闭连接
const closeConn = () => {
  client.close();
};

exports.findDocuments = findDocuments;
exports.findDocumentsLimit = findDocumentsLimit;
exports.insertDocuments = insertDocuments;
exports.findDocumentsById = findDocumentsById;
exports.findDocumentByName = findDocumentByName;
exports.findDocmentByInfo = findDocmentByInfo;
exports.closeConn = closeConn;
